package com.kehutong.admin.util;


import java.util.ArrayList;
import java.util.List;

import org.coraframework.json.JSONObject;
import org.coraframework.orm.Pool;
import org.coraframework.util.EnumUtil;
import org.coraframework.util.Objects;

import com.kehutong.admin.entity.TreeResource;

public class TreeUtil {
	
	
    public static <T extends TreeResource<T>> T getParent(Class<T> clazz, JSONObject jsonObject) {
		return getEntity(clazz, jsonObject, "parent");
	}
    
    public static <T extends TreeResource<T>> T getEntity(Class<T> clazz, JSONObject jsonObject, String name) {
		JSONObject json = jsonObject.getJSONObject(name);
		if (Objects.isEmpty(json)) {
			return null;
		}
		
		return Pool.get(clazz, json.getString("id"));
	}
    
    public static <T extends Enum<T>> T getEnum(Class<T> clazz, JSONObject jsonObject, String name) {
    	JSONObject json = jsonObject.getJSONObject(name);
		if (Objects.isEmpty(json)) {
			return null;
		}
		
		return EnumUtil.getEnum(clazz, json.getString("id"));
    }
	
//	@SuppressWarnings("unchecked")
//	public <T extends TreeEntity> List<String> getParent_ids(T item) {
//		List<String> parent_ids = new ArrayList<>();
//		
//		T supItem = item;
//		while (supItem != null) {
//			if (supItem.getParent_id().equals(parent.getId())) {
//				parent_ids.addAll(0, parent.getParent_ids());
//			} else {
//				supItem = Pool.get((Class<T>)parent.getClass(), supItem.getParent_id());
//				parent_ids.addAll(0, parent.getParent_ids());
//			}
//		}
//		
//		return parent_ids;
//	}
//	
	public static List<String> getParentIds(TreeResource<?> item) {
		List<String> parent_ids = new ArrayList<>();
		
		TreeResource<?> current = item;
		while (current != null) {
			if ("0".equals(current.getParent_id())) {
				break;
			} else {
				parent_ids.add(0, current.getParent_id());
				current = Pool.get(item.getClass(), current.getParent_id());
			}
		}
		
		return parent_ids;
	}
}
